package com.deluxelx.soul.inn.common.util;

import cn.hutool.core.util.StrUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.deluxelx.soul.inn.common.config.JdOssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * OSS文件操作工具类
 *
 * @author liaozihao
 * @date 2024-04-29 14:30
 */
@Component
@Slf4j
public class OssFileUtil {

    @Resource
    private AmazonS3 amazonS3;

    @Resource
    private JdOssConfig jdOssConfig;

    @Value("${oss.budgetName}")
    private String budgetName;

    public String upload(MultipartFile multipartFile, String prefix) {
        String originalFilename = multipartFile.getOriginalFilename();
        log.info("upload filename：{}", originalFilename);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(multipartFile.getContentType());
        objectMetadata.setContentLength(multipartFile.getSize());
        String filename;
        if (StrUtil.isBlank(prefix)) {
            filename = uuidName(originalFilename);
        } else {
            filename = prefix + StrUtil.SLASH + uuidName(originalFilename);
        }
        try {
            amazonS3.putObject(budgetName, filename, multipartFile.getInputStream(), objectMetadata);
            return "https://" + budgetName + StrUtil.DOT + jdOssConfig.getEndpoint() + StrUtil.SLASH + filename;
        } catch (IOException e) {
            log.error("【OssFileUtil.upload】上传文件失败", e);
            throw new RuntimeException(e);
        }
    }

    private String uuidName(String originalFilename) {
        if (StrUtil.isBlank(originalFilename)) {
            throw new RuntimeException("文件格式错误");
        }
        int i = originalFilename.lastIndexOf(".");
        if (i > 0) {
            return UUID.randomUUID() + originalFilename.substring(i);
        }
        throw new RuntimeException("文件格式错误");
    }
}
